package com.unohacha.qqj.fzdr.personal.view.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.huangmin66.rongcloud.RongCloudUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.common.bean.HttpResult;
import com.unohacha.qqj.fzdr.common.bean.MeterialBean3;
import com.unohacha.qqj.fzdr.common.bean.MetrialBean4;
import com.unohacha.qqj.fzdr.common.http.RetrofitManager;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.main.FindDetailActivity2;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class MaterialDetail3Activity extends BaseActivity implements OnRefreshListener, OnLoadmoreListener {


    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_wechat)
    TextView tvWechat;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.tv_send)
    TextView tvSend;
    private String address_id;
    private String member_id;
    private int page = 1;
    private List<MetrialBean4.DataBean> list;
    private MyAdapter adapter;
    private String thumb;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_material_3;
    }

    @Override
    protected void initView() {
        commonTitle.setText("详情资料");
        commonRightImage.setVisibility(View.INVISIBLE);
        list = new ArrayList<>();
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadmoreListener(this);
        address_id = this.getIntent().getStringExtra("address_id");
        member_id = this.getIntent().getStringExtra("member_id");
        recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new MyAdapter(R.layout.item_material3, list);
        recyclerview.setAdapter(adapter);
        getUI();
        getMessage();
    }

    private void getUI() {
        showLoading();
        RetrofitManager.getInstance()
                .MDetail3(member_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .throttleFirst(2, TimeUnit.SECONDS)
                .subscribe(new Action1<HttpResult<MeterialBean3>>() {
                               @Override
                               public void call(HttpResult<MeterialBean3> meterialBean3HttpResult) {
                                   if (meterialBean3HttpResult.getCode() == 1) {
                                       if (null != meterialBean3HttpResult.getData()) {
                                           setUI(meterialBean3HttpResult.getData());
                                       }

                                   }
                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {

                               }
                           }
                );
        hideLoading();
    }

    private void setUI(MeterialBean3 date) {
        tvName.setText(date.getMember_no() + "");
        tvPhone.setText(date.getTelephone() + "");
        thumb = date.getThumb();
        if (date.getTelephone().equals(Prefer.getInstance().getPhone())) {
            tvSend.setVisibility(View.GONE);
        }
        if (null == date.getWx_no()) {
            tvWechat.setText("");
        } else
            tvWechat.setText(date.getWx_no() + "");

    }

    @OnClick({R.id.common_back, R.id.tv_phone, R.id.tv_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.tv_phone:
                if (tvPhone.getText().length() > 0) {
                    Intent intent = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + tvPhone.getText());
                    intent.setData(data);
                    if (ActivityCompat.checkSelfPermission(MaterialDetail3Activity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    startActivity(intent);
                }
                break;
            case R.id.tv_send:
                RongCloudUtils.getInstance().startConversation(MaterialDetail3Activity.this, Conversation.ConversationType.PRIVATE,member_id,tvName.getText().toString());

                getMyNews();

                break;
        }
    }

    //获取个人信息
    private void getMyNews(){
        Map<String,Object> params = new HashMap<>();
        params.put("id",member_id);
        XUtil.Post(UrlConfig.MY_NEW_INFO,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        Gson gson = new Gson();
                        RongCloudUtils.getInstance()
                                .setCurrentUserInfo(new UserInfo(member_id, tvName.getText().toString().trim(), Uri.parse(thumb)));
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private class MyAdapter extends BaseQuickAdapter<MetrialBean4.DataBean, BaseViewHolder> {
        public MyAdapter(int layoutResId, @Nullable List<MetrialBean4.DataBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, MetrialBean4.DataBean item) {
            helper.setText(R.id.tv_money, item.getPrice() + "");
            helper.setText(R.id.tv_time, item.getTime() + "");
        }
    }

    private void getMessage() {
        showLoading();
        RetrofitManager.getInstance()
                .MDetail4(address_id, member_id, page + "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .throttleFirst(2, TimeUnit.SECONDS)
                .subscribe(new Action1<HttpResult<MetrialBean4>>() {
                    @Override
                    public void call(HttpResult<MetrialBean4> metrialBean4HttpResult) {
                        if (metrialBean4HttpResult.getCode() == 1) {
                            if (null != metrialBean4HttpResult.getData().getData()) {
                                list.addAll(metrialBean4HttpResult.getData().getData());
                                adapter.notifyDataSetChanged();
                            }
                        } else if (metrialBean4HttpResult.getCode() == 0) {
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                            ToastUtils.showT(metrialBean4HttpResult.getMessage());
                        }
                        closeRefresh();
                    }
                });
        hideLoading();
    }

    private void closeRefresh() {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.finishRefresh();
        }
        if (mRefreshLayout.isLoading()) {
            mRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page++;
        getMessage();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        page = 1;
        list.clear();
        getMessage();
    }
}
